from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import serializers
from movie.models import Account
from captcha.views import CaptchaStore, captcha_image
from datetime import timedelta
from django.utils import timezone as django_timezone


class MyTokenObtainPairSerializer(TokenObtainPairSerializer):
    captcha = serializers.CharField(max_length=6)
    # """
    # 自定义登录认证，使用自有用户表
    # username、password这两个字段为必传字段因为 DRF 要检查这些字段是否有效
    # """
    # 后台的登录认证
    def validate(self, attrs):
        print(attrs)
        username = attrs['username']
        password = attrs['password']
        captcha = attrs['captcha'].lower()
        image_code = CaptchaStore.objects.filter(response=captcha).first()
        # 将当前时间转换为带有时区信息的对象
        current_time = django_timezone.now()
        five_minute_ago = current_time - timedelta(hours=0, minutes=5, seconds=0)
        user = Account.objects.filter(username=username, password=password).first()
        print('user', user)
        if not user:
            result = {
                "code": 4000,
                "msg": "账号/密码不正确",
            }
            return result
        status = user.status
        if status == '2':
            result = {
                'code': 4000,
                'msg': '账号已被禁用'
            }
            return result
        if image_code and five_minute_ago > image_code.expiration:
            image_code and image_code.delete()
            result = {
                "code": 4000,
                "msg": "验证码过期",
            }
            return result
        else:
            if image_code and (image_code.response == captcha or image_code.challenge == captcha):
                image_code and image_code.delete()
            else:
                image_code and image_code.delete()
                result = {
                    "code": 4000,
                    "msg": "图片验证码错误",
                }
                return result
        refresh = self.get_token(user)
        data = {"userId": user.id,
                'username': user.username,
                "nick_name": user.nick_name,
                "token": str(refresh.access_token),
                'exp': refresh.access_token.payload['exp'],
                "refresh": str(refresh),
                'code': 2000,
                'msg': '登录成功'
                }
        print(data)
        return data
